
matrix orthoProjMatrix;
float3x4 transformMatrix;
texture destTexture;
texture brushTexture;
float4 viewportSize;

sampler textureSampler = sampler_state
{
	Texture = <destTexture>;
	AddressU = CLAMP;
	AddressV = CLAMP;
	AddressW = CLAMP;
	BorderColor = float4(0, 0, 0, 0);
	MipFilter = LINEAR;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
};

sampler brushSampler = sampler_state
{
	Texture = <brushTexture>;
	AddressU = CLAMP;
	AddressV = CLAMP;
	AddressW = CLAMP;
	BorderColor = float4(0, 0, 0, 0);
	MipFilter = LINEAR;
	MinFilter = LINEAR;
	MagFilter = LINEAR;
};

struct VertexShaderInput
{
	float3 position : POSITION0;
	float4 color : COLOR0;
	float2 texCoord : TEXCOORD0;
	float2 texCoordBrush : TEXCOORD1;
};

struct PixelShaderInput
{
	float4 position : POSITION0;
	float2 texCoord : TEXCOORD0;
	float2 texCoordBrush : TEXCOORD2;
	float4 color : TEXCOORD1;
};

void VertexMain(in VertexShaderInput vsInput, out PixelShaderInput output)
{
	output = (PixelShaderInput)0;

	float3 newPosTransform = mul(float3(vsInput.position.xy, 1), float3x3(transformMatrix._11_12_13, transformMatrix._21_22_23, transformMatrix._31_32_33));
	newPosTransform.xy /= newPosTransform.z;

	float4 posTransformed = float4(newPosTransform.xy, 0, 1);
	float xbase = -viewportSize.x / 2.0f;
	float ybase = viewportSize.y / 2.0f;
	posTransformed.x += xbase;
	posTransformed.y = ybase - posTransformed.y;

	output.position = mul(posTransformed, orthoProjMatrix);
	output.texCoord = vsInput.texCoord;
	output.color = vsInput.color;
	output.texCoordBrush = vsInput.texCoordBrush;
}

float4 sampleDiffs(float2 texCoord)
{
	float stepX = 1.0f / 512.0f;
	float stepY = 1.0f / 512.0f;

	// MID
	float4 c1 = tex2D(textureSampler, texCoord);
	float4 c2 = tex2D(textureSampler, float2(texCoord.x, texCoord.y + stepY));
	float4 c3 = tex2D(textureSampler, float2(texCoord.x, texCoord.y - stepY));
	float4 c4 = tex2D(textureSampler, float2(texCoord.x + stepX, texCoord.y));
	float4 c5 = tex2D(textureSampler, float2(texCoord.x - stepX, texCoord.y));
	
	return (c1 + c2 + c3 + c4 + c5) / 5.0f;
}

void PixelMain(in PixelShaderInput input, out float4 color : COLOR0)
{
	float4 texColor = sampleDiffs(input.texCoord);
	/*float3 diff = float3(1, 1, 1) - texColor.rgb;
	float len = 1.0f - dot(diff, diff);
	float alpha = len;*/
	color = tex2D(brushSampler, input.texCoordBrush); //input.color;
	color.a = texColor.a;
}